﻿;
(function (window, angular) {
    'use strict';
    angular.module("Controller.Logistics.WaybillMaintenance", [])
        .controller("WaybillMaintenanceCtrl", ["$scope", "ybWidget", "ybHttp", "MESG_TYPE", "$timeout", "$filter", "UserContextService", function ($scope, ybWidget, ybHttp, MESG_TYPE, $timeout, $filter, UserContextService) {
            $scope.activeFlag = [true, false, false, false, false];
            $scope.markInfo = {
                allCheckedWayBill: false,
                allCheckedBill: false,
                allCheckedMaterial: false
            };
            $scope.toolbarConfig = {
                showAdvanceSearch: false,
                showColConfig: false
            };
            $scope.switchToolbar = function (toolbar) {
                if (!!$scope.toolbarConfig["show" + toolbar]) {
                    $scope.toolbarConfig["show" + toolbar] = false;
                } else {
                    $timeout(function () {
                        $scope.toolbarConfig["show" + toolbar] = true;
                    });
                }
            };

            $scope.selectSingle = function (item, list, type) {
                if (!item.isChecked) {
                    $scope.markInfo["allChecked" + type] = false;
                } else {
                    if (!checkAll(list)) {
                        $scope.markInfo["allChecked" + type] = false;
                    } else {
                        $scope.markInfo["allChecked" + type] = true;
                    }
                }
            };

            $scope.selectAll = function (list, type) {
                angular.forEach(list, function (item) {
                    item.isChecked = $scope.markInfo["allChecked" + type];
                });
            };

            function checkAll(list) {
                var selectAllFlag = false;
                for (var i = 0, len = list.length; i < len; i++) {
                    if (!list[i].isChecked) {
                        selectAllFlag = false;
                        break;
                    }
                    selectAllFlag = true;
                }
                return selectAllFlag;
            }

            $scope.curStep = { val: 0 };

            $scope.detailInfo = {};
            $scope.submitted = false;

            $scope.tabFlag = {};
            var tabFlag = {
                0: "选择发运交接单",
                1: "选择三包出库单",
                2: "新增",
            };
            $scope.exportParam = {
                sectionUrl: ybHttp.RequestUrl("device", "/deliveryNote/exportDetails"),
                sectionParam: { ids: [] },
                allUrl: ybHttp.RequestUrl("device", "/deliveryNote/exportDetailsAll")
            };

            $scope.tableConfig = {
                fixedWidth: 240,
                scrollWidth: 1630,
                tableCol: [
                    {
                        name: "物流运单号",
                        dataField: "wayBillNo",
                        width: 180,
                        isShow: true,
                        isFixed: false,
                        clickFn: "viewDetail",
                    },
                    {
                        name: "客户代码",
                        dataField: "dealerOrgId",
                        width: 150,
                        isShow: true,
                        isFixed: false,
                    },
                    {
                        name: "客户名称",
                        dataField: "dealerOrgName",
                        width: 150,
                        isShow: true,
                        isFixed: false,
                    },
                    {
                        name: "单据状态",
                        dataField: "statusShow",
                        width: 150,
                        isShow: true,
                        isFixed: false,
                    },
                    {
                        name: "初始运费",
                        dataField: "initinalCarriage",
                        width: 150,
                        isShow: true,
                        isFixed: false,
                    },
                    {
                        name: "变更后运费",
                        dataField: "afterModifyCarriage",
                        width: 150,
                        isShow: true,
                        isFixed: false,
                    },
                    {
                        name: "最终运费",
                        dataField: "finalCarriage",
                        width: 150,
                        isShow: true,
                        isFixed: false,
                    },
                    {
                        name: "单据类型",
                        dataField: "billTypeShow",
                        width: 150,
                        isShow: true,
                        isFixed: false,
                    },
                    {
                        name: "单据运输方式",
                        dataField: "shippingMethod",
                        width: 150,
                        isShow: true,
                        isFixed: false,
                    },
                    {
                        name: "承运商",
                        dataField: "carrierOrgName",
                        width: 150,
                        isShow: true,
                        isFixed: false,
                    },
                    {
                        name: "备注",
                        dataField: "remark",
                        width: 150,
                        isShow: true,
                        isFixed: false,
                    },
                    {
                        name: "审核意见",
                        dataField: "auditRemark",
                        width: 150,
                        isShow: true,
                        isFixed: false,
                    },
                    {
                        name: "制单人",
                        dataField: "createUserName",
                        width: 150,
                        isShow: true,
                        isFixed: false,
                    },
                    {
                        name: "制单时间",
                        dataField: "createDateShow",
                        width: 150,
                        isShow: true,
                        isFixed: false,
                    },
                    {
                        name: "审核人",
                        dataField: "auditUserName",
                        width: 150,
                        isShow: true,
                        isFixed: false,
                    },
                    {
                        name: "审核时间",
                        dataField: "auditDateShow",
                        width: 150,
                        isShow: true,
                        isFixed: false,
                    },
                    {
                        name: "发货状态",
                        dataField: "deliveryStatusShow",
                        width: 150,
                        isShow: true,
                        isFixed: false,
                    },
                    {
                        type: "operate",
                        name: "操作",
                        width: 200,
                        isShow: true,
                        isFixed: true,
                    }
                ]
            };
            $scope.tableMaterialConfig = {
                scrollWidth: 1000,
                tableCol: [
                    {
                        name: "零件号",
                        dataField: "materialsNo",
                        width: 150,
                        isShow: true,
                        isFixed: false,
                    },
                    {
                        name: "零件中文名",
                        dataField: "materialsDesc",
                        width: 400,
                        isShow: true,
                        isFixed: false,
                    },
                    {
                        name: "数量",
                        dataField: "amount",
                        width: 150,
                        isShow: true,
                        isFixed: false,
                    },
                    {
                        name: "本次发运数量",
                        dataField: "currentOrderAmount",
                        width: 150,
                        isShow: true,
                        isFixed: false,
                        input: true,
                        inputType: ''
                    },
                    {
                        name: "单据号",
                        dataField: "businessOrderNo",
                        width: 250,
                        isShow: true,
                        isFixed: false,
                    },
                ]
            };

            $scope.setFixedWidth = function () {
                $scope.tbStyle = {
                    scrollLeft: {
                        left: $scope.tableConfig.fixedWidth + "px"
                    }
                };
            };

            $scope.changeTab = function (index) {
                $scope.activeFlag = [false, false, false, false, false];
                $scope.activeFlag[index] = true;
                $scope.submitted = false;
                switch (index) {
                    case 0:
                        initData();
                        break;
                    case 1:
                        break;
                    case 2:
                        break;
                    case 3:
                        break;
                    case 4:
                        break;
                    default:
                        break;
                }
            };

            function initData() {
                $scope.markInfo = {
                    allCheckedWayBill: false,
                    allCheckedBill: false,
                    allCheckedMaterial: false
                };
                $scope.curStep = { val: 0 };
                $scope.billPageInfo = {
                    totalPages: 1,
                    totalRows: 0,
                    pageSize: 10,
                    curPage: 1
                };
                $scope.billCondition = {};
                $scope.billDataList = [];

                $scope.detailInfo = {};
            }


            $scope.pageInfo = {
                totalPages: 1,
                totalRows: 0,
                pageSize: 10,
                curPage: 1
            };
            $scope.condition = {};
            $scope.dataList = [];
            $scope.reset = function () {
                $scope.condition = {};
            };
            $scope.search = function (curpage) {
                getDataList(curpage);
            };
            function getDataList(curPage) {
                var service = "device";
                var reqUrl = "/logisticWayBill/listing";
                var param = {};
                if (!!curPage) {
                    $scope.pageInfo.curPage = curPage;
                }
                param.pageSize = $scope.pageInfo.pageSize;
                param.pageNum = $scope.pageInfo.curPage;
                param.filters = angular.copy($scope.condition);
                if (param.filters.materialsNosList) {
                    param.filters.materialsNosList = param.filters.materialsNosList.split(',')
                }else {
                    param.filters.materialsNosList = []
                }
                ybHttp.Post(service, reqUrl, param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return;
                    }
                    angular.forEach(resp.value.list, function (item) {
                        item.isChecked = false;
                        item.billTypeShow = $filter("orderType")(item.billType);
                        item.statusShow = $filter("WayBillStatus")(item.status);
                        item.createDateShow = $filter("YbDate")(item.createDate, 'yyyy-MM-dd HH:mm:ss');
                        item.auditDateShow = $filter("YbDate")(item.auditDate, 'yyyy-MM-dd HH:mm:ss');
                        item.deliveryStatusShow = $filter("ProgressStatus")(item.deliveryStatus, 'deliveryStatus');
                    });
                    $scope.pageInfo.totalRows = resp.value.total;
                    $scope.pageInfo.totalPages = resp.value.pages;
                    $scope.dataList = resp.value.list;
                });
            }
            $scope.selectRow = function (index) {
                $scope.markInfo.curRow = index
            };
            $scope.tdClick = function (item, fnType) {
                switch (fnType) {
                    case "viewDetail":
                        viewDetail(item);
                        break;
                    default:
                        break;
                }
            };



            $scope.selectBills = function (typeVal) {
                $scope.tabFlag.type = typeVal;
                $scope.tabFlag.name = tabFlag[typeVal];
                getBillsData(1).then(function() {
                    $scope.changeTab(1);
                })
            };
            $scope.billPageInfo = {
                totalPages: 1,
                totalRows: 0,
                pageSize: 10,
                curPage: 1
            };
            $scope.billCondition = {};
            $scope.billDataList = [];
            $scope.billSearch = function () {
                getBillsData();
            };

            function getBillsData(curPage) {
                var service = "device";
                var reqUrl = "/logisticWayBill/selectBusinessBills";
                var param = {};
                if (!!curPage) {
                    $scope.billPageInfo.curPage = curPage;
                }
                param.pageSize = $scope.billPageInfo.pageSize;
                param.pageNum = $scope.billPageInfo.curPage;
                param.filters = {
                    businessType: $scope.tabFlag.type == 0 ? 'XGFJ' : 'XGSC'
                };
                Object.assign(param.filters, $scope.billCondition)
                return ybHttp.Post(service, reqUrl, param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return;
                    }
                    angular.forEach(resp.value.list, function (item) {
                        item.isChecked = false;
                    });
                    $scope.billPageInfo.totalRows = resp.value.total;
                    $scope.billPageInfo.totalPages = resp.value.pages;
                    $scope.billDataList = resp.value.list;
                });
            }

            $scope.orderSelectSingle = function (billTypeVal,no) {
                if (billTypeVal == 1) {
                    // 选择三包出库单
                    var arr = Array.from(new Set($scope.billDataList.filter(f=>f.isChecked).map(m=>m.receiverName)))
                    if (arr.length == 0) {
                        ybWidget.ShowToaster('error', '请选择单据');
                        return
                    }
                    if (arr.length > 1) {
                        ybWidget.ShowToaster('error', '只能选择相同收货人的单据');
                        return
                    }
                }

                var service = "device";
                var reqUrl = "/logisticWayBill/businessOrderSelectedInfo";
                var param = {
                    businessType: billTypeVal == 0 ? 'XGFJ' : 'XGSC',
                    businessOrderNos: billTypeVal == 0 ? no : $scope.billDataList.filter(b=>b.isChecked).map(i=>i.businessOrderNo).join(',')
                };
                ybHttp.Get(service, reqUrl, param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return;
                    }
                    angular.forEach(resp.value.materialses, function (item) {
                        item.isChecked = false;
                    });

                    resp.value.headInfo.businessType = billTypeVal == 0 ? 'XGFJ' : 'XGSC',
                    resp.value.headInfo.dealerOrgId = resp.value.headInfo.dealerOrgId || '454583802384089088',
                    resp.value.headInfo.deliveryTime = resp.value.headInfo.deliveryTime ? new Date(resp.value.headInfo.deliveryTime) : '',
                    $scope.detailInfo = resp.value

                    $scope.tabFlag.name = tabFlag[2];
                    $scope.curStep.val = 1;
                });
            };

            $scope.handleShippingChange = function() {
                $scope.detailInfo.headInfo.unitPrice = ''
                $scope.detailInfo.headInfo.kilometers = ''
                $scope.detailInfo.headInfo.logisticFee = ''
                $scope.detailInfo.headInfo.packagingFee = ''
                $scope.detailInfo.headInfo.handlingCost = ''
                $scope.detailInfo.headInfo.initinalCarriage = ''
            };

            $scope.handleInitinalCarriage = function() {
                var type = $scope.detailInfo.headInfo.shippingMethodId
                var res = 0
                switch(type) {
                    case '0001':
                        res = ($scope.detailInfo.headInfo.unitPrice||0) * ($scope.detailInfo.headInfo.kilometers||0) + Number($scope.detailInfo.headInfo.boxTrunkFee||0)
                        break
                    case '0002':
                    case '0003':
                    case '0004':
                    case '0005':
                    case '0006':
                    case '0007':
                        res = Number($scope.detailInfo.headInfo.logisticFee||0) + Number($scope.detailInfo.headInfo.packagingFee||0) + Number($scope.detailInfo.headInfo.handlingCost||0) + Number($scope.detailInfo.headInfo.boxTrunkFee||0)
                        break
                }
                $scope.detailInfo.headInfo.initinalCarriage = Number(res||0).toFixed(2)
            };

            $scope.selectExpressCode = function () {
                var param = {
                    name: "物流商",
                    type: "logistics"
                };
                ybWidget.SingleSelector(param).then(function (data) {
                    $scope.detailInfo.headInfo.expressCode = data.expressCode;
                })
            };

            $scope.saveData = function (isValid, type) {
                if (!isValid) {
                    $scope.submitted = true;
                    return;
                }
                var selectedData = $scope.detailInfo.materialses.filter(m => m.isChecked)
                if (selectedData && selectedData.length == 0) {
                    ybWidget.ShowToaster('error', '请选择零件');
                    return;
                }

                var service = "device";
                var reqUrl = "/logisticWayBill/saveLogistics";
                if (type == 'submit') {
                    reqUrl = "/logisticWayBill/submitLogistics";
                }
                $scope.detailInfo.headInfo.shippingMethod = $scope.sendMethodList.find(s => s.code == $scope.detailInfo.headInfo.shippingMethodId).name
                var param = {
                    headInfo: $scope.detailInfo.headInfo,
                    materialses: selectedData
                };
                ybHttp.Post(service, reqUrl, param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return;
                    }
                    ybWidget.ShowToaster('success', '操作成功');
                    $scope.changeTab(0);
                    getDataList();
                });
            };

            $scope.getTopCss = function () {
                if (!$scope.detailInfo.headInfo) {
                    return
                }
                var t = $scope.detailInfo.headInfo.shippingMethodId
                if (!!t) {
                    if ($scope.activeFlag[5]) {
                        return (t == '0004' || t == '0007') ? '350px' : '320px'
                    }
                    if ($scope.tabFlag.type==0) {
                        return '410px'
                    }
                    return (t == '0004' || t == '0007') ? '360px' : '300px'
                }

                if ($scope.tabFlag.type==0) {
                    return '320px'
                }
                return '260px'
            };


            $scope.delData = function (val) {
                var service = "device";
                var reqUrl = "/logisticWayBill/remove";
                ybWidget.ShowMessage("确定要删除吗？", MESG_TYPE.Ask).then(function () {
                    ybHttp.Get(service, reqUrl, { id: val }).then(function (resp) {
                        if (resp.code !== 0) {
                            ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                            return;
                        }
                        ybWidget.ShowToaster('success', '操作成功');
                        getDataList();
                    })
                }, function () {})
            };

            $scope.editData = function (val) {
                var service = "device";
                var reqUrl = "/logisticWayBill/editViewInfo";
                ybHttp.Get(service, reqUrl, { id: val }).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return false;
                    }

                    angular.forEach(resp.value.materialses, function (item) {
                        item.isChecked = true;
                    });

                    resp.value.headInfo.deliveryTime = resp.value.headInfo.deliveryTime ? new Date(resp.value.headInfo.deliveryTime) : '';
                    resp.value.headInfo.estimateArrivalDate = resp.value.headInfo.estimateArrivalDate ? new Date(resp.value.headInfo.estimateArrivalDate) : '';
                    $scope.detailInfo = resp.value;

                    $scope.tabFlag.type = resp.value.headInfo.businessType == 'XGFJ' ? 0 : 1;
                    $scope.changeTab(2);
                });
            };

            $scope.modifyData = function (val) {
                var service = "device";
                var reqUrl = "/logisticWayBill/modifyViewInfo";
                ybHttp.Get(service, reqUrl, { id: val }).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return false;
                    }
                    $scope.detailInfo = resp.value
                    $scope.changeTab(3);
                });
            };

            $scope.saveModifyData = function (isValid, type) {
                if (!isValid) {
                    $scope.submitted = true;
                    return;
                }
                var service = "device";
                var reqUrl = "/logisticWayBill/modify/save";
                if (type == 'submit') {
                    reqUrl = "/logisticWayBill/modify/submit";
                }
                ybHttp.Post(service, reqUrl, $scope.detailInfo).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return;
                    }
                    ybWidget.ShowToaster('success', '操作成功');
                    $scope.changeTab(0);
                    getDataList();
                });
            };

            // 删除零件
            $scope.delMateriel = function (index) {
                $scope.detailInfo.materialses.splice(index, 1);
            };


            $scope.auditData = function (val) {
                var service = "device";
                var reqUrl = "/logisticWayBill/editViewInfo";
                ybHttp.Get(service, reqUrl, { id: val }).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return false;
                    }

                    $scope.detailInfo = resp.value.headInfo

                    $scope.changeTab(4);
                });
            };

            $scope.handleAudit = function (isValid, type, ids, msg) {
                if (!isValid) {
                    $scope.submitted = true;
                    return;
                }
                var service = "device";
                var reqUrl = "/logisticWayBill/" + type;
                var params = {
                    ids: ids || [$scope.detailInfo.id],
                    auditRemark: msg || $scope.detailInfo.auditRemark,
                };
                // 单条审核时传最终审核运费
                if (params.ids.length == 1) {
                    params.finalCarriage  = $scope.detailInfo.finalCarriage
                }
                return ybHttp.Post(service, reqUrl, params).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return;
                    }
                    ybWidget.ShowToaster('success', '操作成功');
                    $scope.changeTab(0);
                    getDataList();
                });
            };

            $scope.auditBillBatch = function () {
                var ids = [];
                for (var i = 0, len = $scope.dataList.length; i < len; i++) {
                    if (!!$scope.dataList[i].isChecked) {
                        ids.push($scope.dataList[i].id);
                    }
                }
                if (ids.length === 0) {
                    ybWidget.ShowMessage('请正确选择需要审核的行');
                    return;
                }
                ybWidget.AuditMsg({
                    passCb: function(val) {
                        if (!val) {
                            ybWidget.ShowMessage("请填写审核意见", MESG_TYPE.Error);
                            return Promise.reject();
                        }
                        return $scope.handleAudit(true, 'auditPass', ids, val)
                    },
                    refuseCb: function(val) {
                        return $scope.handleAudit(true, 'auditReject', ids, val)
                    }
                })
            };


            // 点击物流运单号查看详情
            function viewDetail(item) {
                var service = "device";
                var reqUrl = "/logisticWayBill/viewInfo";
                ybHttp.Get(service, reqUrl, { id: item.id }).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return;
                    }
                    $scope.subTabFlag = [true, false, false];
                    $scope.detailInfo = resp.value;
                    $scope.changeTab(5);

                });
            }

            $scope.printSingle = function (val) {
                var billIds = [val];
                var param = {
                    billId: billIds,
                    printType: "WaybillMaintenance"
                };
                ybWidget.SetIsPrintOrPreview(param);
            };

            $scope.deliveryGoods = function (val) {
                ybWidget.ShowDatePicker({name:'预计到货时间'}).then(function(data) {
                    var service = "device";
                    var reqUrl = "/logisticWayBill/deliveryConfirm";
                    var param = {
                        id: val,
                        expectArrivalTime: data
                    };
                    ybHttp.Post(service, reqUrl, param).then(function (resp) {
                        if (resp.code !== 0) {
                            ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                            return;
                        }
                        getDataList()
                    });
                })
            };

            // 选择承运商
            $scope.selectLogisticsCom = function () {
                var param = {
                    name: "承运物流",
                    type: "carrier"
                };
                ybWidget.SingleSelector(param).then(function (data) {
                    $scope.detailInfo.headInfo.carrierOrgId = data.orgId;
                    $scope.detailInfo.headInfo.carrierOrgName = data.companyName;
                })
            };


            // 查询运输方式
            function getSendMethods () {
                var service = "device";
                var reqUrl = "/sendMethodDictionary/list";
                var param = {pId: 0};
                ybHttp.Post(service, reqUrl, param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return;
                    }
                    $scope.sendMethodList = resp.value;
                })
            }

            var btnPermissionCode = {
                waybillMaintenanceEdit: window.ActionCode.waybillMaintenanceEdit,
                waybillMaintenanceChange: window.ActionCode.waybillMaintenanceChange,
                waybillMaintenancePrint: window.ActionCode.waybillMaintenancePrint,
                waybillMaintenanceDel: window.ActionCode.waybillMaintenanceDel,
                waybillMaintenanceAudit: window.ActionCode.waybillMaintenanceAudit,
                waybillMaintenanceShip: window.ActionCode.waybillMaintenanceShip,
            };

            $scope.btnPermission = {
                waybillMaintenanceEdit: true,
                waybillMaintenanceChange: true,
                waybillMaintenancePrint: true,
                waybillMaintenanceDel: true,
                waybillMaintenanceAudit: true,
                waybillMaintenanceShip: true,
            };

            function setBtnPermission() {
                for (var key in btnPermissionCode) {
                    $scope.btnPermission[key] = UserContextService.CheckPermission([btnPermissionCode[key]]);
                }
            }

            (function () {
                getDataList();
                getSendMethods();
                $scope.setFixedWidth();
                UserContextService.SetBtnPermission(setBtnPermission);
            })();
        }]);
})(window, window.angular);
